# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

import datetime
import logging
import os

from google.appengine.ext import webapp
from google.appengine.ext.webapp import template
from google.appengine.ext.webapp import util

ROOT = os.path.dirname(__file__)

def strip(text):
    return text.strip()

def validate_float(text):
    try:
        return float(text)
    except ValueError:
        return

def validate_int(text):
    try:
        return int(text)
    except ValueError:
        return

def validate_timestamp(text):
    time = validate_int(text)
    if time:
        return datetime.datetime.fromtimestamp(time / 1000)

class Struct(dict):
    def __init__(self, **kwargs):
        self.update(kwargs)

    def __getattr__(self, name):
        if name in self:
            return self[name]

    def __setattr__(self, name, value):
        self[name] = value

class Handler(webapp.RequestHandler):

    auto_params = {
        'lat': validate_float,
        'lng': validate_float,
        'signal': validate_int,
        'wifi': validate_int,
        'timestamp': validate_timestamp,
        'provider': strip
    }

    def initialize(self, request, response):
        webapp.RequestHandler.initialize(self, request, response)

        # Initialize parameters
        self.params = Struct()
        for param in self.auto_params:
            validator = self.auto_params[param]
            setattr(self.params, param, validator(request.get(param, '')))

    def render(self, path, **params):
        self.write(self.render_to_string(path, **params))

    def render_to_string(self, path, **params):
        return webapp.template.render(os.path.join(ROOT, path), params)

    def write(self, text):
        self.response.out.write(text)

def run(*args, **kwargs):
    webapp.util.run_wsgi_app(webapp.WSGIApplication(*args, **kwargs))

